//
//  KuanShiTableViewController.m
//  W2MD
//
//  Created by zhudongwei on 14/11/12.
//  Copyright (c) 2014年 zhudongwei. All rights reserved.
//

#import "KuanShiTableViewController.h"
#import "thirdLib/fmdb/FMDB.h"
#import <sqlite3.h>
#import "KSDetailView.h"

static NSString *TopValuesKey = @"topValuesCell";

@interface KuanShiTableViewController ()
{
    NSString *titleName;
    NSString *path;
    NSMutableDictionary *topKeyValue;
    NSMutableDictionary *secKeyValue;
    KSDetailView * ksDetailView;
}
@end

@implementation KuanShiTableViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withName:(NSString*)name
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        titleName = name;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = [NSString stringWithFormat:@"款式选择-%@",titleName];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelBtnClick:)];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneBtnClick:)];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self initDataFromDB];
    
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"KSDetailView" owner:self options:nil];
    ksDetailView = [nib objectAtIndex:0];
    ksDetailView.detailTV.delegate = self;
    ksDetailView.detailTV.dataSource = self;
    
}

-(IBAction)cancelBtnClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(IBAction)doneBtnClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initDataFromDB
{
    [self readyDatabse];
    FMDatabase *db = [FMDatabase databaseWithPath:path];
    if ([db open]) {
        NSString *sql = @"select Pic_BelongsStyle.ID,Pic_BelongsStyle.Name from Pic_BelongsStyle, BelongsType_BelongsStyle where   BelongsType_BelongsStyle.BelongsTypeID=2 and  BelongsType_BelongsStyle.Female_StyleID=Pic_BelongsStyle.ID";
        FMResultSet *result = [db executeQuery:sql];
        
        topKeyValue = [[NSMutableDictionary alloc] init];
        NSMutableDictionary *_mutableDictionayData = [[NSMutableDictionary alloc] init];
        [topKeyValue removeAllObjects];
        [_mutableDictionayData removeAllObjects];
        while ([result next]) {
            _mutableDictionayData = [[NSMutableDictionary alloc] init];
            NSString *sid = [result stringForColumn:@"ID"];
            [_mutableDictionayData setObject:sid forKey:@"ID"];
            
            NSString *name = [result stringForColumn:@"Name"];
            [_mutableDictionayData setObject:name forKey:@"Name"];
            
            [topKeyValue setValue:_mutableDictionayData forKey:name];
        }
        
        [db close];
        [self.tableView reloadData];
    }
    
}

-(void)initLevel2DataFromDB:(NSString*)strID
{
    [self readyDatabse];
    FMDatabase *db = [FMDatabase databaseWithPath:path];
    if ([db open]) {
        NSString *sql = [NSString stringWithFormat:@"select Pic_DetailStyle.ID,Pic_DetailStyle.Name from Pic_DetailStyle, BelongsStyle_DetailStyle where   BelongsStyle_DetailStyle.BelongsStyleId=%@ and  BelongsStyle_DetailStyle.Female_DetailStyleId=Pic_DetailStyle.ID", strID];
        FMResultSet *result = [db executeQuery:sql];
        
        secKeyValue = [[NSMutableDictionary alloc] init];
        NSMutableDictionary *_mutableDictionayData = [[NSMutableDictionary alloc] init];
        [secKeyValue removeAllObjects];
        [_mutableDictionayData removeAllObjects];
        while ([result next]) {
            _mutableDictionayData = [[NSMutableDictionary alloc] init];
            NSString *sid = [result stringForColumn:@"ID"];
            [_mutableDictionayData setObject:sid forKey:@"ID"];
            
            NSString *name = [result stringForColumn:@"Name"];
            [_mutableDictionayData setObject:name forKey:@"Name"];
            
            [secKeyValue setValue:_mutableDictionayData forKey:name];
        }
        
        [db close];
        
        if ([secKeyValue count]>0) {
            [self.view addSubview:ksDetailView];
            [ksDetailView.detailTV reloadData];
        }
    }
    
}

- (void)readyDatabse {
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"dd21.sqlite"];
    success = [fileManager fileExistsAtPath:writableDBPath];
    [self getPath];
    if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"dd21.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

- (void)getPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    path = [documentsDirectory stringByAppendingPathComponent:@"dd21.sqlite"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (tableView == self.tableView) {
        return [[topKeyValue allKeys] count];
    }
    else if(tableView == ksDetailView.detailTV)
    {
        return [[secKeyValue allKeys] count];
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TopValuesKey];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TopValuesKey];
    }
    
    if (tableView == self.tableView) {
        cell.textLabel.text = [[topKeyValue allKeys] objectAtIndex:indexPath.row];
    }
    else if(tableView == ksDetailView.detailTV)
    {
        cell.textLabel.text = [[secKeyValue allKeys] objectAtIndex:indexPath.row];
    }
    
    
    
    // Configure the cell...
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    //<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    //[self.navigationController pushViewController:detailViewController animated:YES];
    if (tableView == self.tableView) {
        //[self.view addSubview:ksDetailView];
        NSString *strID = [[topKeyValue objectForKey:[[topKeyValue allKeys] objectAtIndex:indexPath.row]] objectForKey:@"ID"];
        [self initLevel2DataFromDB:strID];
    }
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
